package com.wyl.servlet

import com.wyl.service.user.UserService
import com.wyl.service.user.UserServiceImpl
import com.wyl.utils.USER_SESSION
import javax.servlet.annotation.WebServlet
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

@WebServlet("/login.do")
class LoginServlet : HttpServlet() {
    private val userService: UserService = UserServiceImpl()

    override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
        val user = userService.login(
            req.getParameter("userCode"),
            req.getParameter("userPassword")
        )
        if (user != null) {
            req.session.setAttribute(USER_SESSION, user)
            resp.sendRedirect("/jsp/frame.jsp")
        } else {
            req.setAttribute("error", "用户名或者密码不正确")
            req.getRequestDispatcher("/login.jsp").forward(req, resp)
        }
    }

    override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
        this.doGet(req, resp)
    }
}